package com.medusa.aps.business.modules.demand.controller;

import cn.hutool.core.util.IdUtil;
import com.medusa.aps.business.model.exception.BusinessErrorCode;
import com.medusa.aps.business.model.pagination.Page;
import com.medusa.aps.business.modules.demand.model.input.*;
import com.medusa.aps.business.modules.demand.model.output.ScheduleDetailOutSourcingModel;
import com.medusa.aps.business.modules.demand.model.output.ScheduleDetailSelfModel;
import com.medusa.aps.business.modules.demand.model.output.SchedulePageListModel;
import com.medusa.aps.business.modules.demand.model.output.ScheduleProcessDetailsVO;
import com.medusa.aps.business.modules.demand.mp.entity.PlanOperationProgress;
import com.medusa.aps.business.modules.demand.service.MrpPlanningOperationService;
import com.medusa.aps.business.modules.demand.service.ScheduleService;
import com.medusa.aps.business.util.PercentageScheduleUtils;
import com.medusa.aps.business.common.model.resp.Result;
import com.medusa.aps.business.common.security.resource.helper.ISecurity;
import com.medusa.aps.business.common.web.valid.group.Create;
import com.medusa.aps.business.global.model.exception.GlobalException;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Size;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.Set;
import java.util.concurrent.CompletableFuture;

/**
 * @author miskw
 * @date 2023/12/27
 */
@Slf4j
@Validated
@RestController
@RequiredArgsConstructor
@RequestMapping("/schedule")
@Tag(name = "排程运算控制层", description = "排程运算控制层")
public class ScheduleController {
    private final ScheduleService scheduleService;
    @Resource
    private MrpPlanningOperationService mrpPlanningOperationService;

    /**
     * 分页查询排程运算列表
     *
     * @param schedulePageQuery 分页参数
     */
    @PostMapping
    @Operation(summary = "分页查询排程运算列表", description = "分页查询排程运算列表")
    public Result<Page<SchedulePageListModel>> schedulePage(@RequestBody @Valid SchedulePageQuery schedulePageQuery) {
        return Result.ok(scheduleService.schedulePage(schedulePageQuery));
    }

    /**
     * 修改排程运算订单数据
     *
     * @param orderParams 订单参数集合
     * @return 修改结果
     */
    @PutMapping("/update")
    @Operation(summary = "修改排程运算订单数据", description = "修改排程运算订单数据")
    public Result<Void> update(@RequestBody @Valid OrderParam orderParams) {
        scheduleService.updateScheduleOrders(orderParams);
        return Result.ok();
    }

    /**
     * 更新订单优先级
     *
     * @param orderIncrement 接收实体
     */
    @PutMapping("/update/increment")
    @Operation(summary = "更新订单优先级", description = "更新订单优先级")
    public Result<Void> updateIncrement(@RequestBody @Valid @NotNull(message = "请选择需要编辑的订单") OrderIncrementParam orderIncrement) {
        scheduleService.updateIncrementScheduleOrder(orderIncrement);
        return Result.ok();
    }

    /**
     * 删除数据
     *
     * @param ids 主键结合
     * @return 删除结果
     */
    @DeleteMapping("/delete")
    @Operation(summary = "删除数据", description = "删除数据")
    public Result<Void> removeScheduleOrders(@RequestBody @Size(min = 1, max = 50, message = "限制同时操作1-50条数据") Set<Long> ids) {
        scheduleService.removeScheduleOrders(ids);
        return Result.ok();
    }

    /**
     * 排程明细-自制生产
     *
     * @param controlDetailParam 排程明细接收参数
     */
    @GetMapping("/self/control")
    @Operation(summary = "排程明细-自制生产列表")
    public Result<Page<ScheduleDetailSelfModel>> selfControl(@Validated(Create.class) ControlDetailParam controlDetailParam) {
        return Result.ok(scheduleService.selfControl(controlDetailParam, new Page<>(controlDetailParam.getCurrent(), controlDetailParam.getSize())));
    }

    /**
     * 排程明细-外购/委外生产
     *
     * @param controlDetailParam 排程明细接收参数
     */
    @GetMapping("/un-self/control")
    @Operation(summary = "排程明细-外购/委外生产列表")
    public Result<Page<ScheduleDetailOutSourcingModel>> unSelfControl(@Valid ControlDetailParam controlDetailParam) {
        if(controlDetailParam.getProductionType()==null){
            throw new GlobalException("生产类型不能为空");
        }
        return Result.ok(scheduleService.unSelfControl(controlDetailParam, new Page<>(controlDetailParam.getCurrent(), controlDetailParam.getSize())));
    }

    /**
     * 排程明细-工序明细列表
     *
     * @param scheduleProcessDetailsParam 参数
     */
    @GetMapping("/process/detail")
    @Operation(summary = "排程明细-工序明细列表")
    public Result<Page<ScheduleProcessDetailsVO>> scheduleProcessDetail(@Valid ScheduleProcessDetailsParam scheduleProcessDetailsParam) {
        return Result.ok(scheduleService.scheduleProcessDetail(scheduleProcessDetailsParam));
    }

    /**
     * 释放占用物料
     *
     * @param id 订单id
     */
    @PutMapping("/release/occupation/material")
    @Operation(summary = "释放占用物料", description = "释放占用物料")
    public Result<BigDecimal> releaseOccupationMaterial(@RequestParam("id") @NotNull(message = "请选择需要释放物料的订单") Integer id) {
        return Result.ok(scheduleService.releaseOccupationMaterial(id));
    }

    @PostMapping("/mrpPlaningOperation")
    @Operation(summary = "计划运算", description = "计划运算")
    public Result<Long> mrpPlaningOperation(@RequestBody PlanningOperationParam planningOperationParam) {
        PercentageScheduleUtils.validClassSystemGenerateCalendar();
        Long id = IdUtil.getSnowflakeNextId();
        Authentication authentication = ISecurity.getAuthentication(true);
        CompletableFuture.runAsync(() -> {
            try {
                SecurityContext context = SecurityContextHolder.createEmptyContext();
                context.setAuthentication(authentication);
                SecurityContextHolder.setContext(context);
                mrpPlanningOperationService.mrpPlaningOperation(id, planningOperationParam);
            } catch (Exception e) {
                log.error("排程异常:", e);
                String failureReason = e.getMessage();
                if (e instanceof IllegalMonitorStateException) {
                    failureReason = BusinessErrorCode.GET_LOCK_FAIL.getMsg();
                } else if (!(e instanceof GlobalException)) {
                    failureReason = "排程异常，请联系技术人员！";
                }
                mrpPlanningOperationService.updatePlanOperationProgress(id, failureReason);
            } finally {
                SecurityContextHolder.clearContext();
            }
        });
        return Result.ok(id);
    }

    @GetMapping("/planOperationProgress")
    @Operation(summary = "计划运算进度", description = "计划运算进度")
    public Result<PlanOperationProgress> planTaskOperation(@RequestParam("id") long id) {
        return Result.ok(mrpPlanningOperationService.planOperationProgress(id));
    }

    @GetMapping("/checkPurchasePlan")
    @Operation(summary = "检查采购计划", description = "检查采购计划")
    public Result<String> checkPurchasePlan(@RequestParam("orderNumbers") Set<String> orderNumbers) {
        return Result.ok(mrpPlanningOperationService.checkPurchasePlan(orderNumbers));
    }

}
